"""
主动服务
实现基于用户行为的主动服务推荐、提醒和预测性服务提供
"""

from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
import asyncio
import logging
from sqlalchemy.orm import Session
from uuid import UUID

from src.services.user_preference_service import UserPreferenceService
from src.services.notification_service import NotificationService
from src.services.research_service import ResearchService
from src.services.service_orchestrator import ServiceOrchestrator
from src.models.user import User
from src.utils.logging import get_logger
from src.config.database import get_db

logger = get_logger(__name__)


class ProactiveService:
    """主动服务类"""
    
    def __init__(self):
        self.user_preference_service = UserPreferenceService()
        self.notification_service = NotificationService()
        self.research_service = ResearchService()
        self.service_orchestrator = ServiceOrchestrator()
        self.recommendation_cache: Dict[str, Any] = {}
        
    async def analyze_user_behavior(self, user_id: UUID) -> Dict[str, Any]:
        """
        分析用户行为模式
        
        Args:
            user_id: 用户ID
            
        Returns:
            用户行为分析结果
        """
        try:
            # 获取用户交互记录
            behavior_patterns = await self._get_user_behavior_patterns(user_id)
            
            # 分析用户偏好趋势
            preferences = self.user_preference_service.get_user_preferences(int(user_id))
            
            # 结合历史行为和偏好生成行为画像
            behavior_profile = {
                "user_id": str(user_id),
                "activity_level": behavior_patterns.get("activity_level", "medium"),
                "preferred_services": behavior_patterns.get("preferred_services", []),
                "interaction_frequency": behavior_patterns.get("interaction_frequency", {}),
                "active_periods": behavior_patterns.get("active_periods", []),
                "preferences": preferences
            }
            
            return behavior_profile
        except Exception as e:
            logger.error(f"分析用户行为失败: {e}")
            return {}
    
    async def _get_user_behavior_patterns(self, user_id: UUID) -> Dict[str, Any]:
        """
        获取用户行为模式
        
        Args:
            user_id: 用户ID
            
        Returns:
            用户行为模式数据
        """
        try:
            # 从数据库获取用户最近30天的交互记录
            # 这里应该查询UserInteractionRecord表
            # 为简化实现，返回模拟数据
            return {
                "activity_level": "high",
                "preferred_services": ["research", "knowledge_base"],
                "interaction_frequency": {
                    "daily": 5.5,
                    "weekly": 38,
                    "monthly": 150
                },
                "active_periods": ["09:00-12:00", "14:00-18:00"]
            }
        except Exception as e:
            logger.error(f"获取用户行为模式失败: {e}")
            return {}
    
    async def generate_proactive_recommendations(self, user_id: UUID, limit: int = 5) -> List[Dict[str, Any]]:
        """
        生成主动推荐
        
        Args:
            user_id: 用户ID
            limit: 推荐数量限制
            
        Returns:
            推荐列表
        """
        try:
            # 分析用户行为
            behavior_profile = await self.analyze_user_behavior(user_id)
            
            # 基于行为画像生成推荐
            recommendations = []
            
            # 根据用户偏好的服务类型生成推荐
            preferred_services = behavior_profile.get("preferred_services", [])
            if "research" in preferred_services:
                # 为研究服务生成推荐
                research_recommendations = await self._generate_research_recommendations(user_id, behavior_profile)
                recommendations.extend(research_recommendations)
                
            if "knowledge_base" in preferred_services:
                # 为知识库服务生成推荐
                kb_recommendations = await self._generate_knowledge_base_recommendations(user_id, behavior_profile)
                recommendations.extend(kb_recommendations)
            
            # 根据用户活跃时间生成提醒推荐
            time_based_recommendations = await self._generate_time_based_recommendations(user_id, behavior_profile)
            recommendations.extend(time_based_recommendations)
            
            # 生成上下文相关推荐
            context_recommendations = await self._generate_context_based_recommendations(user_id, behavior_profile)
            recommendations.extend(context_recommendations)
            
            # 按相关性排序并返回前N个
            recommendations.sort(key=lambda x: x.get("relevance_score", 0), reverse=True)
            return recommendations[:limit]
        except Exception as e:
            logger.error(f"生成主动推荐失败: {e}")
            return []
    
    async def _generate_research_recommendations(self, user_id: UUID, behavior_profile: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        生成研究服务推荐
        
        Args:
            user_id: 用户ID
            behavior_profile: 用户行为画像
            
        Returns:
            研究服务推荐列表
        """
        try:
            # 基于用户历史查询和偏好生成研究主题推荐
            recommendations = []
            
            # 获取用户偏好主题
            preferences = behavior_profile.get("preferences", {})
            topic_preferences = {k: v for k, v in preferences.items() if k.startswith("topic_")}
            
            # 基于热门主题和用户偏好生成推荐
            for topic_key, topic_data in list(topic_preferences.items())[:3]:
                topic = topic_data['value']
                recommendations.append({
                    "type": "research_topic",
                    "title": f"深入了解 {topic}",
                    "description": f"基于您对{topic}的兴趣，为您推荐相关内容",
                    "service": "research",
                    "relevance_score": topic_data.get('weight', 1.0),
                    "action": f"research_query_{topic}",
                    "metadata": {
                        "topic": topic
                    }
                })
            
            return recommendations
        except Exception as e:
            logger.error(f"生成研究推荐失败: {e}")
            return []
    
    async def _generate_knowledge_base_recommendations(self, user_id: UUID, behavior_profile: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        生成知识库推荐
        
        Args:
            user_id: 用户ID
            behavior_profile: 用户行为画像
            
        Returns:
            知识库推荐列表
        """
        try:
            recommendations = []
            
            # 基于用户访问频率生成文档推荐
            recommendations.append({
                "type": "knowledge_base",
                "title": "您可能感兴趣的知识文档",
                "description": "根据您的浏览历史，推荐相关文档",
                "service": "knowledge_base",
                "relevance_score": 0.8,
                "action": "view_recommended_docs",
                "metadata": {}
            })
            
            return recommendations
        except Exception as e:
            logger.error(f"生成知识库推荐失败: {e}")
            return []
    
    async def _generate_time_based_recommendations(self, user_id: UUID, behavior_profile: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        生成基于时间的推荐
        
        Args:
            user_id: 用户ID
            behavior_profile: 用户行为画像
            
        Returns:
            时间相关推荐列表
        """
        try:
            recommendations = []
            
            # 获取用户活跃时间段
            active_periods = behavior_profile.get("active_periods", [])
            
            # 根据活跃时间生成提醒
            for period in active_periods:
                recommendations.append({
                    "type": "reminder",
                    "title": "每日知识更新提醒",
                    "description": f"在您的活跃时间 {period} 提供最新知识更新",
                    "service": "notification",
                    "relevance_score": 0.7,
                    "action": "daily_update_reminder",
                    "metadata": {
                        "preferred_time": period
                    }
                })
            
            return recommendations
        except Exception as e:
            logger.error(f"生成时间相关推荐失败: {e}")
            return []
    
    async def _generate_context_based_recommendations(self, user_id: UUID, behavior_profile: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        生成基于上下文的推荐
        
        Args:
            user_id: 用户ID
            behavior_profile: 用户行为画像
            
        Returns:
            上下文相关推荐列表
        """
        try:
            recommendations = []
            
            # 根据当前时间生成推荐
            current_time = datetime.now()
            hour = current_time.hour
            
            # 早上推荐任务规划
            if 8 <= hour <= 10:
                recommendations.append({
                    "type": "context",
                    "title": "晨间任务规划",
                    "description": "新的一天开始了，为您规划今日学习任务",
                    "service": "task_planning",
                    "relevance_score": 0.85,
                    "action": "plan_daily_tasks",
                    "metadata": {
                        "time_context": "morning"
                    }
                })
            
            # 下午推荐知识更新
            elif 14 <= hour <= 16:
                recommendations.append({
                    "type": "context",
                    "title": "下午知识充电时间",
                    "description": "为您推荐最新的行业资讯和知识更新",
                    "service": "knowledge_update",
                    "relevance_score": 0.8,
                    "action": "afternoon_knowledge_update",
                    "metadata": {
                        "time_context": "afternoon"
                    }
                })
            
            # 晚上推荐总结回顾
            elif 19 <= hour <= 21:
                recommendations.append({
                    "type": "context",
                    "title": "今日学习总结",
                    "description": "回顾您今天的学习内容，巩固知识点",
                    "service": "learning_summary",
                    "relevance_score": 0.75,
                    "action": "daily_learning_summary",
                    "metadata": {
                        "time_context": "evening"
                    }
                })
            
            return recommendations
        except Exception as e:
            logger.error(f"生成上下文相关推荐失败: {e}")
            return []
    
    async def send_proactive_notification(self, user_id: UUID, recommendation: Dict[str, Any]) -> bool:
        """
        发送主动通知
        
        Args:
            user_id: 用户ID
            recommendation: 推荐内容
            
        Returns:
            是否发送成功
        """
        try:
            # 构造通知内容
            notification_title = recommendation.get("title", "为您推荐")
            notification_content = recommendation.get("description", "")
            
            # 获取用户对象
            db_generator = get_db()
            db = next(db_generator)
            user = db.query(User).filter(User.id == user_id).first()
            
            if not user:
                logger.warning(f"未找到用户 {user_id}")
                return False
            
            # 发送通知
            success = await self.notification_service.send_proactive_recommendation(user, recommendation)
            if success:
                logger.info(f"向用户 {user_id} 发送主动通知成功: {notification_title}")
            else:
                logger.error(f"向用户 {user_id} 发送主动通知失败: {notification_title}")
            
            return success
        except Exception as e:
            logger.error(f"发送主动通知失败: {e}")
            return False
    
    async def predict_user_needs(self, user_id: UUID) -> List[Dict[str, Any]]:
        """
        预测用户需求
        
        Args:
            user_id: 用户ID
            
        Returns:
            预测的用户需求列表
        """
        try:
            # 分析用户行为模式
            behavior_profile = await self.analyze_user_behavior(user_id)
            
            # 使用服务协调器预测用户可能需要的服务
            predicted_services = []
            
            # 基于用户活跃度和偏好预测
            activity_level = behavior_profile.get("activity_level", "medium")
            preferred_services = behavior_profile.get("preferred_services", [])
            
            if activity_level == "high":
                # 高活跃用户可能需要更高级的功能
                predicted_services.extend([
                    {
                        "service": "advanced_research",
                        "confidence": 0.85,
                        "reason": "用户活跃度高，可能需要高级功能"
                    },
                    {
                        "service": "collaboration",
                        "confidence": 0.75,
                        "reason": "高活跃用户可能希望与他人协作"
                    }
                ])
            
            # 基于偏好服务预测
            for service in preferred_services:
                if service == "research":
                    predicted_services.append({
                        "service": "research_advanced",
                        "confidence": 0.8,
                        "reason": "用户偏好研究服务，可能需要高级研究功能"
                    })
                elif service == "knowledge_base":
                    predicted_services.append({
                        "service": "knowledge_graph",
                        "confidence": 0.7,
                        "reason": "用户偏好知识库，可能对知识图谱感兴趣"
                    })
            
            # 基于时间上下文预测
            current_time = datetime.now()
            hour = current_time.hour
            
            # 工作时间预测
            if 9 <= hour <= 18:
                predicted_services.append({
                    "service": "quick_query",
                    "confidence": 0.7,
                    "reason": "工作时间，用户可能需要快速查询功能"
                })
            
            # 学习时间预测
            if 19 <= hour <= 22:
                predicted_services.append({
                    "service": "deep_learning",
                    "confidence": 0.65,
                    "reason": "晚间时间，用户可能需要深度学习功能"
                })
            
            return predicted_services
        except Exception as e:
            logger.error(f"预测用户需求失败: {e}")
            return []
    
    async def schedule_proactive_services(self):
        """
        调度主动服务任务
        """
        try:
            # 定期分析用户行为并发送推荐
            while True:
                # 这里应该获取所有活跃用户
                # 简化实现，仅作为示例
                logger.info("执行主动服务调度任务")
                
                # 每小时执行一次
                await asyncio.sleep(3600)
        except Exception as e:
            logger.error(f"调度主动服务任务失败: {e}")